package com.dg.gallery

import grails.util.Holders

import com.db.gallery.Project
import com.db.gallery.ProjectGroup
import com.db.gallery.ProjectImage
import com.dg.tools.ImageDataHolder
import com.dg.tools.ImageUtility

class GalleryController {
	
	def grailsApplication
	
	def index() {
		
	}

    def gallery() {
		def dataMap = [:]
		
		List<ProjectGroup> projectGroupList = ProjectGroup.findAll([sort: "id", order: "desc"])
		List<GalleryProjectGroup> galleryProjectGroupList = []
		
		for (projectGroup in projectGroupList) {
			if (projectGroup.projects?.size() > 0) {
				GalleryProjectGroup galleryProjectGroup = new GalleryProjectGroup(projectGroup)
				galleryProjectGroupList.add(galleryProjectGroup)
			}
		}
		
		dataMap.put("editMode", params.editMode)
		dataMap.put("galleryProjectGroups", galleryProjectGroupList)
		
		return dataMap
	}
	
	def project() {
		def dataMap = [:]
		long projectId = params.projectId?.toLong()
		
		Project project = Project.findWhere(id : projectId, [sort: "id", order: "desc"])
		
		GalleryProject galleryProject = new GalleryProject(project)
		
		dataMap.put("galleryProject", galleryProject)
		
		return dataMap
	}
	
	def getUploaderThumbnail() {
		String projectImageIdString = params.id
		Long projectImageId = Long.valueOf(projectImageIdString)
		
		ProjectImage projectImage = ProjectImage.findWhere(id: projectImageId)
		
		ImageDataHolder image = ImageUtility.getImage(projectImage.thumbnailPath, 80)
		
		response.contentType = "image/" + image.getImageType()
		response.outputStream << image.getImagePixelData()
		response.outputStream.flush()
	}
	
	def getImageById() {
		String projectImageIdString = params.id
		Long projectImageId = Long.valueOf(projectImageIdString)
		
		ProjectImage projectImage = ProjectImage.findWhere(id: projectImageId)
		
		ImageDataHolder image = ImageUtility.getImage(projectImage.imagePath)
		
		response.contentType = "image/" + image.getImageType()
		response.outputStream << image.getImagePixelData()
		response.outputStream.flush()
	}
	
	def getImageByPath() {
		ImageDataHolder image = ImageUtility.getImage(params.imagePath)
		
		response.contentType = "image/" + image.getImageType()
		response.outputStream << image.getImagePixelData()
		response.outputStream.flush()
	}
}
